package com.gwsdk.paysdk.acitvityV2.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.gwsdk.open.AuthenticationResult;
import com.gwsdk.open.GWApi;
import com.gwsdk.paysdk.acitvityV2.GWMainMenuActivity;
import com.gwsdk.paysdk.acitvityV2.GWPayActivity;
import com.gwsdk.paysdk.bean.AntiAddictionModel;
import com.gwsdk.paysdk.bean.HelperBean;
import com.gwsdk.paysdk.bean.LoginModel;
import com.gwsdk.paysdk.bean.UserInfoBean;
import com.gwsdk.paysdk.bean.privacy.PrivacyManager;
import com.gwsdk.paysdk.common.Constant;
import com.gwsdk.paysdk.config.GWConstant;
import com.gwsdk.paysdk.dialog.realname.GWCertificationDialog;
import com.gwsdk.paysdk.entity.AntiAddiction;
import com.gwsdk.paysdk.entity.ChannelAndGameinfo;
import com.gwsdk.paysdk.entity.UserLogin;
import com.gwsdk.paysdk.entity.UserPTBInfo;
import com.gwsdk.paysdk.http.RequestParamUtil;
import com.gwsdk.paysdk.http.RequestUtil;
import com.gwsdk.paysdk.http.process.HelperProcess;
import com.gwsdk.paysdk.http.process.SmallAccountListProgress;
import com.gwsdk.paysdk.http.process.UserInfoProcess;
import com.gwsdk.paysdk.http.process.UserPtbBalanceProcess;
import com.gwsdk.paysdk.utils.AppStatusManager;
import com.gwsdk.paysdk.utils.AppUtils;
import com.gwsdk.paysdk.utils.GWInflaterUtils;
import com.gwsdk.paysdk.utils.GWLog;
import com.gwsdk.paysdk.utils.JsonUtil;
import com.gwsdk.paysdk.utils.PreSharedManager;
import com.gwsdk.paysdk.utils.SharedPreferencesUtils;
import com.gwsdk.paysdk.utils.TextUtils;
import com.gwsdk.paysdk.utils.ToastUtil;
import com.gwsdk.paysdk.utils.WebViewUtil;
import com.gwsdk.paysdk.view.round.NiceImageView;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.apache.http.entity.StringEntity;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class GWUserInfoFragment extends GWBaseFragment implements View.OnClickListener{

    private View billItem;
    private NiceImageView avatarImage;
    private SwipeRefreshLayout refreshLayout;

    private TextView smallTV;
    private TextView phoneTV;
    private TextView nickNameTV;
    private TextView balanceTV;
    private TextView ageStatusTV;
    private TextView versionTV;

    private TextView changeAccountBtn;
    private View badge_view,server_view;
    private Switch aSwitch;
    private BitmapUtils bitmapUtils;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public int setContentView() {
        return GWInflaterUtils.getLayout(getActivity(),"gw_fragment_user_info");
    }

    @Override
    public void initView(View view) {

        bitmapUtils = new BitmapUtils(getActivity());

        billItem = view.findViewById(GWInflaterUtils.getControl(getActivity(),"bill_item"));
        billItem.setOnClickListener(this);
        view.findViewById(GWInflaterUtils.getControl(getActivity(),"item_small")).setOnClickListener(this);
        view.findViewById(GWInflaterUtils.getControl(getActivity(),"item_gift")).setOnClickListener(this);
        view.findViewById(GWInflaterUtils.getControl(getActivity(),"item_coupon")).setOnClickListener(this);
        view.findViewById(GWInflaterUtils.getControl(getActivity(),"age_status_view")).setOnClickListener(this);
        view.findViewById(GWInflaterUtils.getControl(getActivity(),"txt_btn_protoal")).setOnClickListener(this);
        view.findViewById(GWInflaterUtils.getControl(getActivity(),"txt_btn_agreement")).setOnClickListener(this);
        view.findViewById(GWInflaterUtils.getControl(getActivity(),"server")).setOnClickListener(this);
        ageStatusTV = view.findViewById(GWInflaterUtils.getControl(getActivity(),"age_status"));
        balanceTV = view.findViewById(GWInflaterUtils.getControl(getActivity(),"bind_balance"));
        smallTV = view.findViewById(GWInflaterUtils.getControl(getActivity(),"small_num"));
        nickNameTV = view.findViewById(GWInflaterUtils.getControl(getActivity(),"user_name"));
        phoneTV = view.findViewById(GWInflaterUtils.getControl(getActivity(),"phone"));
        avatarImage = view.findViewById(GWInflaterUtils.getControl(getActivity(),"avatar"));
        versionTV = view.findViewById(GWInflaterUtils.getControl(getActivity(),"tv_version"));
        badge_view = view.findViewById(GWInflaterUtils.getControl(getActivity(),"badge_view"));
        server_view = view.findViewById(GWInflaterUtils.getControl(getActivity(),"server_view"));
        avatarImage.setCornerRadius(25);
        aSwitch = view.findViewById(GWInflaterUtils.getControl(getActivity(),"switch_auto_login"));
        changeAccountBtn = view.findViewById(GWInflaterUtils.getControl(getActivity(),"change_account_btn"));
        changeAccountBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
                GWApi.getApi().loginout(GWApi.getApi().getContext());

            }
        });

        refreshLayout = view.findViewById(GWInflaterUtils.getControl(getActivity(),"swipe_refresh"));
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshLayout.setRefreshing(false);
            }
        });

        Boolean isRemember = SharedPreferencesUtils.getInstance().isRemember(getActivity());
        aSwitch.setChecked(isRemember);
        aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SharedPreferencesUtils.getInstance().setRemember(getActivity(),isChecked);
            }
        });

        versionTV.setText(AppStatusManager.appStatusManager.version);

    }

    @Override
    public void getData() {
        UserLogin userLogin = PreSharedManager.getUserInfo(getActivity());
        String phone = SharedPreferencesUtils.getInstance().getLoginAccount(getActivity());
        if (userLogin != null){
            nickNameTV.setText(userLogin.getNickname());
            smallTV.setText(userLogin.getSmallAccountList().size() + "");
            balanceTV.setText(userLogin.getBind_balance()+"");
            if (!TextUtils.isEmpty(userLogin.getUserIcon())){
                bitmapUtils.display(avatarImage,userLogin.getUserIcon());
            }
        }
        if (phone != null){
            phoneTV.setText(phone);
        }
        if (AppStatusManager.getInstance().helperBean == null){
            HelperProcess helperProcess = new HelperProcess();
            helperProcess.post(mHandler);
            server_view.setVisibility(View.GONE);
        }
    }



    @Override
    public void onResume() {
        super.onResume();

        refreshUserInfo();

        SmallAccountListProgress progress = new SmallAccountListProgress();
        progress.post(mHandler);

        UserPtbBalanceProcess ptbBalanceProcess = new UserPtbBalanceProcess();//请求平台币、绑币余额信息
        ptbBalanceProcess.post(coinHandler);

        AntiAddiction addiction = LoginModel.instance().getAddiction();
        if (addiction != null){
//            1该用户ID不存在 0未审核 (1审核未通过) 2成年 3未成年  4认证状态等待中
            if (addiction.getAge_status() == 0){
                ageStatusTV.setText("未认证");
            }else if (addiction.getAge_status() == 2){
                ageStatusTV.setText("已认证");
            }else if (addiction.getAge_status() == 1){
                ageStatusTV.setText("审核未通过");
            }else if (addiction.getAge_status() == 3){
                ageStatusTV.setText("已认证(未成年)");
            }else if (addiction.getAge_status() == 4){
                ageStatusTV.setText("等待认证中");
            }
        }else {
            UserLogin userLogin = PreSharedManager.getUserInfo(getActivity());
            if (userLogin.getAge_status() == 0){
                ageStatusTV.setText("未认证");
            }else if (userLogin.getAge_status() == 2){
                ageStatusTV.setText("已认证");
            }else if (userLogin.getAge_status() == 1){
                ageStatusTV.setText("审核未通过");
            }else if (userLogin.getAge_status() == 3){
                ageStatusTV.setText("已认证(未成年)");
            }else if (userLogin.getAge_status() == 4){
                ageStatusTV.setText("等待认证中");
            }
        }
    }

    public void refreshUserInfo(){

        HttpUtils http = new HttpUtils();

        Map<String, String> map = new HashMap<String, String>();
        String param = RequestParamUtil.getRequestParamString(map);
        RequestParams params = new RequestParams();
        try {
            params.setBodyEntity(new StringEntity(param.toString()));
        } catch (UnsupportedEncodingException e) {
            params = null;
        }

        if (params == null) return;
        final String url = GWConstant.getInstance().getRefreshUserInfoUrl();

        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String response= RequestUtil.getResponseAndUrl(responseInfo, url);
                try {
                    JSONObject json = new JSONObject(response);
                    int status=json.optInt("code");
                    if(status==200){

                        JSONObject data = json.getJSONObject("data");

                        if (data != null){
                            nickNameTV.setText(data.getString("nickname"));
                            Glide.with(getActivity()).load(data.getString("head_img")).into(avatarImage);
                        }

                    }
                }  catch (Exception e) {

                }
            }
            @Override
            public void onFailure(HttpException error, String msg) {
                Log.e("downUrl",msg);
            }
        });

    }

    private final Handler coinHandler = new Handler(Looper.getMainLooper(), new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == Constant.PTB_BALANCE_SUCCESS) {
                UserPTBInfo userPtb = (UserPTBInfo) msg.obj;
                balanceTV.setText(String.format(Locale.CHINA, "%.0f", userPtb.getPtbMoney()));;
            }
            return false;
        }
    });


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constant.SMALLACCOUNT_LIST_SUCCESS: //获取小号列表数据成功
                    List<UserLogin.SmallAccountEntity> smallAccountList = (List<UserLogin.SmallAccountEntity>) msg.obj;
                    smallTV.setText(smallAccountList.size() + "");
                    break;
                case Constant.HELPER_SUCCESS:
                    AppStatusManager.getInstance().helperBean = (HelperBean) msg.obj;
                    server_view.setVisibility(View.VISIBLE);
                    break;
            }
        }
    };




    @Override
    public void onClick(View view) {
        GWMainMenuActivity activity = (GWMainMenuActivity) getActivity();
        if (view.getId() == GWInflaterUtils.getControl(getActivity(),"bill_item")){
            GWBillFragment billFragment = new GWBillFragment();
            activity.addOtherFragment(billFragment);
        }else if (view.getId() == GWInflaterUtils.getControl(getActivity(),"item_gift")){

            GWMineGiftFragment giftFragment = new GWMineGiftFragment();
            activity.addOtherFragment(giftFragment);
        }else if (view.getId() == GWInflaterUtils.getControl(getActivity(),"item_small")){
            GWSmallAccountFragment billFragment = new GWSmallAccountFragment();
            activity.addOtherFragment(billFragment);
        }else if (view.getId() == GWInflaterUtils.getControl(getActivity(),"item_coupon")){
            GWMineCouponFragment couponFragment = new GWMineCouponFragment();
            activity.addOtherFragment(couponFragment);
        }else if (view.getId() == GWInflaterUtils.getControl(getActivity(),"age_status_view")){

            AntiAddiction addiction = LoginModel.instance().getAddiction();
            if (addiction != null){

                if (addiction.getAge_status() == 0){
                    new GWCertificationDialog(GWApi.getApi().getContext(), addiction.getContents_off(), false).show();
                    getActivity().finish();
                }
            }else {
                UserLogin userLogin = PreSharedManager.getUserInfo(getActivity());
                if (userLogin.getAge_status() == 0){
                    new GWCertificationDialog(GWApi.getApi().getContext(), "", false).show();
                    getActivity().finish();
                }
            }
        }else if (view.getId() == GWInflaterUtils.getControl(getActivity(),"txt_btn_agreement")){
            WebViewUtil.webView(getActivity(), PrivacyManager.getInstance().agreeUrl(), true);
            getActivity().finish();
        }else if (view.getId() == GWInflaterUtils.getControl(getActivity(),"txt_btn_protoal")){
            WebViewUtil.webView(getActivity(), PrivacyManager.getInstance().privacyUrl(), true);
            getActivity().finish();
        }else if (view.getId() == GWInflaterUtils.getControl(getActivity(),"server")){
            GWCustomerServerFragment serverFragment = new GWCustomerServerFragment();
            activity.addOtherFragment(serverFragment);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

}
